package leetcode_1601_1700;

public class LeeCode_1638 {
    public static void main(String[] args) {
        System.out.println(countSubstrings2("aba", "baba"));
        System.out.println(countSubstrings2("ab", "bb"));
        System.out.println(countSubstrings2("a", "a"));
        System.out.println(countSubstrings2("abe", "bbc"));
    }
    private static int countSubstrings(String s, String t) {
        int len = s.length();
        int res = 0;
        for (int i = 0; i < len; i++) {
            int l = 0, r = l + i;
            while (r < len){
                for (int j = i; j < t.length(); j++) {
                    int lt = j - i;
                    int count = 0;
                    for (int k = 0; k <= i; k++) {
                        if (s.charAt(l + k) != t.charAt(lt + k)){
                            count++;
                        }
                    }
                    if (count == 1)
                        res++;
                }
                l++;
                r++;
            }
        }
        return res;
    }

    private static int countSubstrings2(String s, String t) {
        int res = 0;
        int m = s.length();
        int n = t.length();
        int[][] dp = new int[m][n];
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (s.charAt(i) == t.charAt(j))
                    dp[i][j] = -1;
            }
        }
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (s.charAt(i) == t.charAt(j))
                    continue;
                int ls = i - 1, lt = j - 1, rs = i + 1, rt = j + 1, cl = 1, cr = 1;
                while (ls >= 0 && lt >= 0 && dp[ls][lt] == -1){
                    cl++;
                    ls--;
                    lt--;
                }
                while (rs < m && rt < n && dp[rs][rt] == -1){
                    cr++;
                    rs++;
                    rt++;
                }
                res += cl * cr;
            }
        }
        return res;
    }
}
